package com.sky.controller.user;

import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import com.sky.web.controller.BaseController;
import com.sky.web.domain.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author tzl
 * @Date 2023-07-14 20:40:44  星期五
 * @Description: 微信用户相关接口
 */
@Slf4j
@Api(tags = "微信用户相关接口")
@RestController
@RequestMapping("/user/user")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;


    /**
     * 微信用户登陆
     * @param dto 微信用户登陆信息
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "微信用户登陆接口")
    public AjaxResult login(@RequestBody UserLoginDTO dto){
        log.info("微信用户登陆，{}",dto.getCode());
        //微信登陆
        User user = userService.wxLogin(dto);

        //生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        claims.put(JwtClaimsConstant.NAME, user.getName());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);

        UserLoginVO loginVO = UserLoginVO.builder()
                .id(user.getId())
                .token(token)
                .openid(user.getOpenid())
                .build();
        return AjaxResult.success(loginVO);
    }
}
